"""
此脚本用于gac环境监控系统业务

"""
import hashlib
import traceback
import hmac
import json
from datetime import datetime
from urllib import parse
import time
import requests

host = "pre-ad-data-agw.gacicv.com"
leaf_ids = []
error_id = []


def getapiheader(URI, query, method):
    """
    通过aksk获取header
    """
    query = "&".join(sorted(query.split("&")))
    AK = "0afe4445b872404393695122bc0b30e5"
    SK = '2cb1b6b1770b40899675cbc8157b4f16'

    # 2.x-bce-date
    x_bce_date = time.gmtime()
    x_bce_date = time.strftime('%Y-%m-%dT%H:%M:%SZ', x_bce_date)
    # 3.header和signedHeaders
    header = {
        "Host": host,
        "content-type": "application/json;charset=utf-8",
        "x-bce-date": x_bce_date
    }
    signedHeaders = "content-type;host;x-bce-date"
    # 4.认证字符串前缀
    authStringPrefix = "bce-auth-v1" + "/" + AK + "/" + x_bce_date + "/" + "1800"
    # 5.生成CanonicalRequest
    # 5.1生成CanonicalURI
    CanonicalURI = parse.quote(URI)  # windows下为urllib.parse.quote，Linux下为urllib.quote
    # 5.2生成CanonicalQueryString
    CanonicalQueryString = query  # 如果您调用的接口的query比较复杂的话，需要做额外处理
    # 5.3生成CanonicalHeaders
    result = []
    for key, value in header.items():
        tempStr = str(parse.quote(key.lower(), safe="")) + ":" + str(parse.quote(value, safe=""))
        result.append(tempStr)
    result.sort()
    CanonicalHeaders = "\n".join(result)
    # 5.4拼接得到CanonicalRequest
    CanonicalRequest = method + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders
    # 6.生成signingKey
    signingKey = hmac.new(SK.encode('utf-8'), authStringPrefix.encode('utf-8'), hashlib.sha256)
    # 7.生成Signature
    Signature = hmac.new((signingKey.hexdigest()).encode('utf-8'), CanonicalRequest.encode('utf-8'), hashlib.sha256)
    # 8.生成Authorization并放到header里
    header['Authorization'] = authStringPrefix + "/" + signedHeaders + "/" + Signature.hexdigest()
    return header


def adsaggregate():
    URI = "/v1/scene/ads/aggregate"
    url = "http://" + host + URI
    response = requests.request("GET", url, headers=getapiheader(URI, "", "GET"))



if __name__ == '__main__':
    pass